package ru.housewife.service.dishes;

import org.hibernate.Session;
import ru.common.hibernate.HibernateAction;
import ru.housewife.form.CookingDishRecipeForm;
import ru.housewife.form.EatingMenuDishRecipeForm;
import ru.housewife.form.EatingMenuForm;
import ru.housewife.form.UserForm;
import ru.housewife.model.CookingDishRecipe;
import ru.housewife.model.EatingMenu;
import ru.housewife.model.EatingMenuDishRecipe;

/**
 * modifies eating menu - adds dish to it
 *
 * @author Alexander Troshanin
 */
public class AddDishToEatingMenu implements HibernateAction<EatingMenuDishRecipe> {

    private EatingMenuForm eatingMenuForm;
    private CookingDishRecipeForm recipeForm;
    private UserForm userForm;

    public AddDishToEatingMenu(EatingMenuForm eatingMenuForm, UserForm userForm, CookingDishRecipeForm recipeForm) {
        this.eatingMenuForm = eatingMenuForm;
        this.userForm = userForm;
        this.recipeForm = recipeForm;
    }

    @Override
    public EatingMenuDishRecipe execute(Session session) {

        EatingMenu eatingMenu = (EatingMenu) session.get(EatingMenu.class, eatingMenuForm.getId());
        if (eatingMenu == null) {
            return null;
        }
        CookingDishRecipe recipe;
        if (recipeForm.getId() > 0) {
            recipe = (CookingDishRecipe) session.get(CookingDishRecipe.class, recipeForm.getId());
            if (recipe == null) {
                return null;
            }
        } else {
            recipe = new AddNewCookingDishRecipe(userForm, recipeForm).execute(session);
            if (recipe == null) {
                return null;
            }
            recipeForm = userForm.getUsersCookingDishRecipeForm(recipe.getId());
        }

        EatingMenuDishRecipe eatingMenuRecipe = new EatingMenuDishRecipe();
        eatingMenuRecipe.setEatingMenu(eatingMenu);
        eatingMenuRecipe.setRecipe(recipe);
        session.save(eatingMenuRecipe);

        eatingMenu.getEatingMenuRecipes().add(eatingMenuRecipe);
        session.save(eatingMenu);

        session.flush();

        eatingMenuForm.addEatingMenuRecipe(new EatingMenuDishRecipeForm(eatingMenuRecipe.getId(), eatingMenuForm, recipeForm));

        return eatingMenuRecipe;

/*
        EatingMenuDishRecipeForm existingEatingMenuRecipe = eatingMenuForm.getEatingMenuRecipeByRecipeId(recipeForm.getId());

        if (existingEatingMenuRecipe == null) {
        } else {
            existingEatingMenuRecipe.setCount(existingEatingMenuRecipe.getCount() + 1);
            return new UpdateEatingMenuDishCount(existingEatingMenuRecipe).execute(session);
        }
*/
    }
}
